/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.meta.controller.func;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.je.common.base.DynaBean;
import com.je.common.base.mapper.query.Condition;
import com.je.common.base.mapper.query.Query;
import com.je.common.base.mvc.AbstractPlatformController;
import com.je.common.base.mvc.BaseMethodArgument;
import com.je.common.base.result.BaseRespResult;
import com.je.common.base.result.DirectJsonResult;
import com.je.common.base.util.MessageUtils;
import com.je.common.base.util.StringUtil;
import com.je.core.entity.extjs.JSONTreeNode;
import com.je.meta.service.func.FuncPermService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * 功能数据权限配置
 */
@RestController
@RequestMapping(value = "/je/meta/funcPerm")
public class FuncPermSettingController extends AbstractPlatformController {

    @Autowired
    private FuncPermService funcPermService;

    @Override
    @RequestMapping(value = "/load", method = RequestMethod.POST)
    public BaseRespResult load(BaseMethodArgument param, HttpServletRequest request) {
        Query query = param.buildQuery();
        List<Condition> conditionList =query.getCustom();
        for(Condition condition:conditionList){
           String value = condition.getValue()==null?"":condition.getValue().toString();
           if(StringUtil.isNotEmpty(value)){
               JSONArray jsonArray = JSON.parseArray(value);
               for(int i = 0;i<jsonArray.size();i++){
                   JSONObject jsonObject = jsonArray.getJSONObject(i);
                   String itemCode = jsonObject.getString("code");
                   String itemValue = jsonObject.getString("value");
                   if("SY_PATH".equals(itemCode)&&!itemValue.contains("/")){
                       jsonArray.remove(jsonObject);
                       JSONObject item = new JSONObject();
                       item.put("code","SY_PRODUCT_ID");
                       item.put("type","=");
                       item.put("value",jsonObject.getString("value"));
                       jsonArray.add(item);
                   }
               }
               condition.setValue(jsonArray);
           }
        }
        query.setCustom(conditionList);
        param.setjQuery(JSON.toJSONString(query));
        return super.load(param,request);
    }

    @RequestMapping(value = "/getTree", method = RequestMethod.POST)
    public BaseRespResult loadTree(BaseMethodArgument param, HttpServletRequest request) {
        JSONTreeNode tree =funcPermService.getTree(param,request);
        if (tree != null) {
            return BaseRespResult.successResult(DirectJsonResult.buildObjectResult(tree));
        } else {
            return BaseRespResult.successResult(DirectJsonResult.buildObjectResult("{}"));
        }
    }

    /**
     * 根据功能获取 字段编码名称
     *
     * @return
     */
    @RequestMapping(value = "/getFuncFieldDic", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public BaseRespResult getFuncFieldDic(HttpServletRequest request) {
        String funcId = getStringParameter(request,"FUNCPERM_FUNCINFO_ID");
        Boolean en = false;
        Cookie jeLang = org.springframework.web.util.WebUtils.getCookie(request, "je-local-lang");
        if (jeLang != null) {
            if ("en".equals(jeLang.getValue())) {
                en = true;
            }
        }
        List<Map<String,Object>> list = funcPermService.getFuncFieldDic(funcId,en);
        return BaseRespResult.successResult(list);
    }


    /**
     * 保存权限
     */
    @RequestMapping(value = "/doSavePerm", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public BaseRespResult doSavePerm(BaseMethodArgument param ,HttpServletRequest request) {
        DynaBean dynaBean = (DynaBean) request.getAttribute("dynaBean");
        dynaBean.setStr("type",getStringParameter(request,"type"));
        funcPermService.doUpdatePerm(dynaBean);
        return BaseRespResult.successResult(MessageUtils.getMessage("common.save.success"));
    }

    /**
     * 获取数据
     * @param request
     * @return
     */
    @RequestMapping(value = "/getPermData", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public BaseRespResult getPermData(HttpServletRequest request) {
        Boolean en = false;
        Cookie jeLang = org.springframework.web.util.WebUtils.getCookie(request, "je-local-lang");
        if (jeLang != null) {
            if ("en".equals(jeLang.getValue())) {
                en = true;
            }
        }
        DynaBean dynaBean = (DynaBean) request.getAttribute("dynaBean");
        String type = getStringParameter(request,"type");
        dynaBean.setStr("type",type);
        dynaBean.set("en",en);
        List<DynaBean> fastAuthList = funcPermService.getPermData(dynaBean);
        return BaseRespResult.successResult(fastAuthList);
    }

    /**
     * 清空数据
     * @param request
     * @return
     */
    @RequestMapping(value = "/restoreDefault", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public BaseRespResult restoreDefault(HttpServletRequest request) {
        String funcCode = getStringParameter(request,"funcCode");
        funcPermService.restoreDefault(funcCode);
        return BaseRespResult.successResult(MessageUtils.getMessage("common.operation.success"));
    }

}
